<template>
  <div class="topBox">
    <div class="title">
      <div class="leftTitle">质检详情<span class="templateStatus"  v-if="props.templateStatus === 1">（引用模板已删除，仅提供查看功能）</span></div>
      <div class="rightDot">
        <span class="dotOne"></span>
        <span class="text">客户侧</span>
        <span class="dotTwo"></span>
        <span class="text">座席侧</span>
      </div>
    </div>

    <div class="top" ref="top">
      <div :class="`wave-surfer-1`" class="flex items-center">
      </div>
    </div>

    <audio-play
      ref="childModal"
      :audioSrc="props.audioSrc"
      :time="time"
      @play="play"
      @forward="forward"
      @back="back"
      @setRate="setRate"
      @playDuration="playDuration"
      @setVolume="setVolume"
    ></audio-play>
  </div>
</template>

<!--suppress JSVoidFunctionReturnValueUsed -->
<script setup>
import {nextTick, onMounted, onUnmounted, ref, watch} from 'vue'
import AudioPlay from './audioPlay.vue'
import { usePageStore } from '@/pinia/page.js'
const store = usePageStore()
import WaveSurfer from 'wavesurfer.js';
import {debounce} from "lodash";
import { useMenuList } from '@/pinia/menu.js'
const {
  VITE_USER_NODE_ENV,
  VITE_AUDIO_CC1_URL,
  VITE_AUDIO_CC1_API,
  VITE_AUDIO_CC2_URL,
  VITE_AUDIO_CC2_API,
  VITE_AUDIO_TNCs_URL,
  VITE_AUDIO_TNCs_API,
  VITE_AUDIO_Test_URL,
  VITE_AUDIO_Test_API
} = import.meta.env

const props = defineProps({
  audioArray:Array,
  audioSrc:String,
  templateStatus: Number
})

const childModal = ref(null)
let time = ref(0)
let wavesurfer = [];
const render = (selector, url) => {
  // 解决上一通下一通导致之前波形纹未消失
  let isHasEl = document.getElementsByClassName('waveform')
  if (isHasEl.length > 0) {
    wavesurfer.stop()
    store.$patch({ currentPlayTime: null})
    childModal.value.setPlayStatus(false)
    let self = isHasEl[0];
    self.parentNode.removeChild(self);
  }



  let domEl = document.createElement('div');
  domEl.setAttribute('class', 'waveform');
  document.querySelector(selector).appendChild(domEl);

  wavesurfer = WaveSurfer.create({
    container: domEl,
    waveColor: '#C2C2C2',
    progressColor: 'rgba(255, 192, 97, 1)',
    cursorColor: 'rgba(105, 105, 105, 1)',
    height: 45,
    barWidth: 2,
    barMinHeight: 1,
    barGap: 1,
  });

  wavesurfer.load(url);
  wavesurfer.on('error', function (e) {
    console.warn(e);
  });
  wavesurfer.on('ready', function () {
    time.value =  wavesurfer.getDuration()
  });
  wavesurfer.on('pause', function () {
    if(store.audioPlayInterval.end) {
      store.$patch({ audioPlayInterval: { start: null , end: null}})
      childModal.value.setPlayStatus(false)
    }
  });
  wavesurfer.on('audioprocess', function() {
    let time = wavesurfer.getCurrentTime();
    store.$patch({ currentPlayTime: time})
  })
  return wavesurfer
}

const playMusic = (flag) => {
  if(flag) {
    wavesurfer.play(); // 播放
  } else {
    wavesurfer.playPause(); // 暂停
  }
}

let mateAudioSrc = ref()
watch(() => props.audioSrc, (newVal, oldVal) => {
  let src = ''
  let url = newVal.toString()
  console.log('NODE_ENV', VITE_USER_NODE_ENV)
  if(VITE_USER_NODE_ENV === 'development') {
    if(url.indexOf(VITE_AUDIO_CC1_URL) !== -1) {
      src = url.replace(VITE_AUDIO_CC1_URL, VITE_AUDIO_CC1_API)
    } else if(url.indexOf(VITE_AUDIO_CC2_URL) !== -1) {
      src = url.replace(VITE_AUDIO_CC2_URL, VITE_AUDIO_CC2_API)
    } else if(url.indexOf(VITE_AUDIO_TNCs_URL) !== -1) {
      src = url.replace(VITE_AUDIO_TNCs_URL, VITE_AUDIO_TNCs_API)
    } else if (url.indexOf(VITE_AUDIO_Test_URL) !== -1) {
      src = url.replace(VITE_AUDIO_Test_URL, VITE_AUDIO_Test_API)
    } else {
      src = newVal
    }
  } else {
    src = newVal
  }

  mateAudioSrc.value = src
  render('.wave-surfer-1', src);
})

// 暂停 ｜ 播放
const play = (value) => {
  playMusic(value)
}
// 快进
const forward = () => {
  if(store.currentPlayTime + 15 >= time.value) {
    wavesurfer.stop()
    childModal.value.setPlayStatus(false)
    store.$patch({ currentPlayTime: null})
  } else {
    wavesurfer.skipForward(15)
  }
}
// 快退
const back = () => {
  wavesurfer.skipBackward(15)
}
// 设置倍率
const setRate = (value) => {
  wavesurfer.setPlaybackRate(value);
}
// 设置声音
const setVolume = (value) => {
  wavesurfer.setVolume(value);
}

// 单条对话播放或者暂停
const playDuration = (flag, time) => {
  wavesurfer.play(time.start, time.end)
  // if(!wavesurfer.isPlaying()) {
  //   childModal.value.setPlayStatus(false)
  // }

}
// 图形缩放
const zoom = () => {
  if(document.getElementsByTagName("canvas")) {
    let el = document.getElementsByTagName("canvas")[0].offsetWidth
    let el2 = document.getElementsByTagName("wave")[0].offsetWidth
    wavesurfer.zoom(el2 / el)
  }
}

onMounted(() => {
  window.addEventListener('resize', resize)
})

const resize = () => {
  debounce(zoom, 300)()
}

watch(() => useMenuList().collapseStatus, (newVal, oldVal) => {
  nextTick(() => resize())
})

onUnmounted(() => {
  window.removeEventListener('resize', resize)
  wavesurfer.stop(); // 暂停
})
</script>

<style lang="scss" scoped>
.topBox {
  background-color: rgba(255, 255, 255, 1) !important;
  width: 100%;
  height: 140px;
  border-radius: 4px;
  .title {
    padding: 18px 19px 17px 19px;
    display: flex;
    .leftTitle {
      flex: 1;
      font-size: 16px;
      font-weight: 600;
      color: rgba(51, 51, 51, 1);
      .templateStatus {
        font-size: 15px;
        color: #E34D59;
      }
    }
    .rightDot {
      margin-left: auto;
      display: flex;
      align-items: center;
      .dotOne {
        display: inline-block;
        width: 10px;
        height: 10px;
        border-radius: 10px;
        background-color: rgba(255, 192, 97, 1);
        margin-right: 3px;
      }
      .dotTwo {
        display: inline-block;
        width: 10px;
        height: 10px;
        border-radius: 10px;
        background-color: rgba(117, 170, 255, 1);
        margin-right: 3px;
        margin-left: 8px;
      }
      .text {
        display: inline-block;
        font-size: 12px;
        font-weight: 500;
        color: rgba(92, 91, 91, 1);
      }
    }
  }

  .line{
    width: 1px;
    height: 45px;
    background-color: #333;

    float: left;
    position: relative;
    top: 0;
    left: 21px;

    // animation: move 10s linear;
  }

  .top{
    // height: 21px; //双轨道的高度
    height: 45px;
    margin: 0 21px;
    border-radius: 8px;
    background-color: #FFF6E6;
  }

  .bottom{
    height: 21px;
    margin: 3px 21px 0;
    background-color: #F5F8FF;
  }
}

@keyframes move {
  0% {
    transform: translateX(0px);
  }
  100% {
    transform: translateX(1500px);
  }
}
.waveform {
  //width: 100%;
}
</style>
